<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,100分)- 分割数组的最大差值（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给定一个由若干整数组成的数组nums &#xff0c;可以在数组内的任意位置进行分割&#xff0c;将该数组分割成两个非空子数组&#xff08;即左数组和右数组&#xff09;&#xff0c;分别对子数组求和得到两个值&#xff0c;计算这两个值的差值&#xff0c;请输出所有分割方案中&#xff0c;差值最大的值。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行输入数组中元素个数n&#xff0c;1 &lt; n ≤ 100000<br /> 第二行输入数字序列&#xff0c;以空格进行分隔&#xff0c;数字取值为4字节整数</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出差值的最大取值</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">6<br /> 1 -2 3 4 -9 7</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">10</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>将数组 nums 划分为两个非空数组的可行方案有:</p> <p>左数组 &#61; [1] 且 右数组 &#61; [-2,3,4,-9,7]&#xff0c;和的差值 &#61; | 1 - 3 | &#61; 2<br /> 左数组 &#61; [1,-2] 且 右数组 &#61; [3,4,-9,7]&#xff0c;和的差值 &#61; | -1 - 5 | &#61;6<br /> 左数组 &#61; [1,-2,3] 且 右数组 &#61; [4,-9,7]&#xff0c;和的差值 &#61; | 2 - 2 | &#61; 0<br /> 左数组 &#61; [1,-2,3,4] 且右数组&#61;[-9,7]&#xff0c;和的差值 &#61; | 6 - (-2) | &#61; 8&#xff0c;<br /> 左数组 &#61; [1,-2,3,4,-9] 且 右数组 &#61; [7]&#xff0c;和的差值 &#61; | -3 - 7| &#61; 10最大的差值为10</p> </td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>我的解题思路如下&#xff1a;</p> 
<p>定义一个leftSum&#xff0c;用于统计左数组的和&#xff0c;初始为0</p> 
<p>定义一个rightSum&#xff0c;用于统计右数组的和&#xff0c;初始为sum(nums)</p> 
<p>然后&#xff0c;开始从 i &#61; 0&#xff0c;开始遍历输入的数组nums的每一个元素nums[i]&#xff0c;</p> 
<p>leftSum &#43;&#61; nums[i]</p> 
<p>rightSum -&#61; nums[i]</p> 
<p>然后计算两个和的差值绝对值diff&#xff0c;比较最大的maxDiff&#xff0c;若大于maxDiff&#xff0c;则maxDiff &#61; diff</p> 
<p>之后&#xff0c;在 i&#43;&#43;&#xff0c;循环上面逻辑&#xff0c;直到 i &#61; nums.length-2&#xff0c;因为左右数组不能为空&#xff0c;因此右数组至少有一个nums[nums.length-1]元素</p> 
<p></p> 
<p>上面算法是一个O(n)时间复杂度&#xff0c;对于1 &lt; n ≤ 100000数量级而言&#xff0c;不会超时。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 2) {
    const n &#61; parseInt(lines[0]);
    const nums &#61; lines[1].split(&#34; &#34;).map(Number);

    console.log(getResult(nums, n));

    lines.length &#61; 0;
  }
});

function getResult(nums, n) {
  let leftSum &#61; 0;
  let rightSUm &#61; nums.reduce((a, b) &#61;&gt; a &#43; b);

  let maxDiff &#61; 0;
  for (let i &#61; 0; i &lt; n-1; i&#43;&#43;) {
    leftSum &#43;&#61; nums[i];
    rightSUm -&#61; nums[i];

    const diff &#61; Math.abs(leftSum - rightSUm);
    if (diff &gt; maxDiff) maxDiff &#61; diff;
  }

  return maxDiff;
}
</code></pre> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; Integer.parseInt(sc.nextLine());
    long[] nums &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToLong(Long::parseLong).toArray();

    System.out.println(getResult(nums, n));
  }

  public static long getResult(long[] nums, int n) {
    long leftSum &#61; 0;
    long rightSum &#61; Arrays.stream(nums).sum();

    long maxDiff &#61; 0;

    for (int i &#61; 0; i &lt; n - 1; i&#43;&#43;) {
      leftSum &#43;&#61; nums[i];
      rightSum -&#61; nums[i];

      long diff &#61; Math.abs(leftSum - rightSum);
      if (diff &gt; maxDiff) maxDiff &#61; diff;
    }

    return maxDiff;
  }
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
nums &#61; list(map(int, input().split()))


# 算法入口
def getResult():
    leftSum &#61; 0
    rightSum &#61; sum(nums)

    maxDiff &#61; 0

    for i in range(n-1):
        leftSum &#43;&#61; nums[i]
        rightSum -&#61; nums[i]

        diff &#61; abs(leftSum - rightSum)
        maxDiff &#61; max(maxDiff, diff)

    return maxDiff


# 算法调用
print(getResult())
</code></pre> 
<p></p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

#define MAX_SIZE 100000
#define MAX(a,b) a &gt; b ? a : b
#define DIFF_ABS(a, b) a &gt; b ? a - b : b - a

long getResult(long* nums, int n);
long sum(long* arr, int arr_size);

int main()
{
	int n;
	scanf(&#34;%d&#34;, &amp;n);
	
	long nums[MAX_SIZE];
	for(int i&#61;0; i&lt;n; i&#43;&#43;) {
		scanf(&#34;%ld&#34;, &amp;nums[i]);
	}
	
	printf(&#34;%ld\n&#34;, getResult(nums, n));
	
	return 0;
}

long getResult(long* nums, int n)
{
	long leftSum &#61; 0;
	long rightSum &#61; sum(nums, n);
	
	long maxDiff &#61; 0;
	
	for(int i&#61;0; i&lt;n-1; i&#43;&#43;) {
		leftSum &#43;&#61; nums[i];
		rightSum -&#61; nums[i];
		
		long diff &#61; DIFF_ABS(leftSum, rightSum);
		maxDiff &#61; MAX(maxDiff, diff);
	}
	
	return maxDiff;
}

long sum(long* arr, int arr_size)
{
	long ans &#61; 0;
	
	for(int i&#61;0; i&lt;arr_size; i&#43;&#43;) {
		ans &#43;&#61; arr[i];
	}
	
	return ans;
}</code></pre> 
<p></p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>